<?php

namespace app\merchants\controller;

use app\common\validate\virtual\VirtualPromoProductValid;
use app\common\validate\virtual\VirtualPromoSpecialValid;
use app\common\validate\virtual\VirtualPromoValid;
use app\merchants\loader\Services;
use think\Exception;

/**
 * 虚码管理
 */
class Virtual extends ApiBase
{
    /**
     * 虚码规则分页列表
     */
    public function page()
    {
        try {
            $options = $this->makePromoWhere();
            $page = Services::Virtual()->getPromoPage($options);
            api_result($page);
        } catch (Exception $e) {
            api_result($e);
        }
    }

    /**
     * 虚码规则列表
     */
    public function list()
    {
        $data = input('get.');
        try {
            $where[] = ['mer_id' , '=' , $this->adminUser['mer_id']];

            if (!empty($data['status']) || (int)$data['status'] === 0){
                $where[] = ['status' , '=' , $data['status']];
            }
            if (!empty($data['id'])){
                $where[] = ['id' , '=' , $data['id']];
            }
            if (empty($data['limit']) || $data['limit'] === 0){
                $data['limit'] = 10;
            }

            if (!empty($data['keyword'])){
                $where[] = ['title' , 'like' , '%' . trim($data['keyword']) . '%'];
            }

            $page = Services::Virtual()->getPromoList($where , $data['limit']);
            api_result($page);
        } catch (Exception $e) {
            api_result($e);
        }
    }

    /**
     * @title 根据请求,生成条件
     */
    private function makePromoWhere(): array
    {
        $params = $this->request->get();
        $options = $this->formatOption($params);
        $where['mer_id'] = $this->adminUser['mer_id'];
        //名称
        if (!empty($params['keyword'])) {
            $where['title'] = ['like', '%' . trim($params['keyword']) . '%'];
        }
        //根据时间搜索
        if (!empty($param['stime']) && empty($param['etime'])) {
            $where['create_time'] = ['>=', $param['stime']];
        }
        if (empty($param['stime']) && !empty($param['etime'])) {
            $where['create_time'] = ['<=', $param['etime']];
        }
        if (!empty($param['stime']) && !empty($param['etime'])) {
            $where['create_time'] = ['between time', [$param['stime'], $param['etime']]];
        }
        //商品code
        if (!empty($params['product_code'])) {
            $mer_id = $this->adminUser['mer_id'];
            $where['id'] = ['in', function ($query) use ($params, $mer_id) {
                $query->name('virtual_promo_product')->where('product_code', $params['product_code'])->where('mer_id', $mer_id)->field('vp_id');
            }];
        }
        $options['where'] = $where;
        return $options;
    }

    /**
     * 虚码规则详情
     */
    public function info()
    {
        try {
            $id = $this->request->get('id', 0);
            if (empty($id)) {
                api_exception(400, 'ID不能为空');
            }
            $page = Services::Virtual()->getPromoInfo(['where' => ['id' => $id, 'mer_id' => $this->adminUser['mer_id']]]);
            api_result($page);
        } catch (Exception $e) {
            api_result($e);
        }
    }

    /**
     * 虚码规则编辑
     */
    public function save()
    {
        try {
            $params = $this->request->post();
            $params['mer_id'] = $this->adminUser['mer_id'];
            $params['op_user'] = $this->adminUser['admin_id'];
            $scene = '.add';
            if (!empty($params['id'])) {
                unset($params['op_user']);
                $scene = '.edit';
            }
            $this->validate($params, VirtualPromoValid::class . $scene);

            $array = [
                'option' => [
                    'small_ticket' => $params['option']['small_ticket'] ?: 0 ,
                    'recheck_record' =>  $params['option']['recheck_record'] ?: 0
                ],
                'salesman' => [
                    'red_packet' => $params['salesman']['red_packet'] ?: 0,
                    'point' => $params['salesman']['point'] ?: 0,
                    'day_num' => $params['salesman']['day_num'] ?: 0
                ],
                'begin_time' => $params['begin_time'] ?: date('Y-m-d H:i:s'),
                'end_time' => $params['end_time'] ?: date('Y-m-d H:i:s', strtotime("+10 year")),
            ];

            $params = array_merge($params,$array);
            $id = Services::Virtual()->savePromo($params);
            api_result(['id' => $id]);
        } catch (Exception $e) {
            api_result($e);
        }
    }

    /**
     * 虚码活动编辑状态
     */
    public function edit_status()
    {
        try {
            $params = $this->request->post();
            $this->validate($params, VirtualPromoValid::class . '.edit_status');
            $id = Services::Virtual()->editPromoStatus(['id' => $params['id'], 'mer_id' => $this->adminUser['mer_id']], ['status' => $params['status']]);
            api_result(['id' => $id]);
        } catch (Exception $e) {
            api_result($e);
        }
    }

    /**
     * 刷新活动状态，禁用已失效活动
     */
    public function edit_all_status()
    {
        try {
            Services::Virtual()->updatePromoAllStatus($this->adminUser['mer_id']);
            api_result([]);
        } catch (Exception $e) {
            api_result($e);
        }
    }

    /**
     * 虚码规则删除
     */
    public function del()
    {
        try {
            $id = $this->request->post('id', 0);
            if (empty($id)) {
                api_exception(400, 'ID不能为空');
            }
            Services::Virtual()->delPromo(['id' => $id, 'mer_id' => $this->adminUser['mer_id']]);
            api_result([]);
        } catch (Exception $e) {
            api_result($e);
        }
    }

    /**
     * 虚码活动商品列表
     */
    public function product_page()
    {
        try {
            $params = $this->request->get();
            if (empty($params['vp_id'])) {
                api_exception(400, '活动ID不能为空');
            }
            $options = $this->formatOption($params);
            $where['vp_id'] = $params['vp_id'];
            $where['mer_id'] = $this->adminUser['mer_id'];
            if (!empty($params['keyword'])) {
                $map[] = ['code|title', 'like', '%' . trim($params['keyword']) . '%'];
                $map[] = ['mer_id', '=', $this->adminUser['mer_id']];
                $where['product_code'] = ['in', function ($query) use ($map) {
                    $query->name('product')->where($map)->field('code');
                }];
            }
            $options['where'] = $where;
            $page = Services::Virtual()->getPromoProductPage($options, $this->adminUser['mer_id']);
            api_result($page);
        } catch (Exception $e) {
            api_result($e);
        }
    }

    /**
     * 虚码活动商品编辑
     */
    public function product_save()
    {
        try {
            $params = $this->request->post();
            $params['mer_id'] = $this->adminUser['mer_id'];
            $params['op_user'] = $this->adminUser['admin_id'];
            $scene = '.add';
            if (!empty($params['id'])) {
                unset($params['op_user']);
                $scene = '.edit';
            }
            $this->validate($params, VirtualPromoProductValid::class . $scene);
            Services::Virtual()->savePromoProduct($params);
            api_result([]);
        } catch (Exception $e) {
            api_result($e);
        }
    }

    /**
     * 虚码活动商品删除
     */
    public function product_del()
    {
        try {
            $params = $this->request->post();
            if (empty($params['id'])) {
                api_exception(400, 'ID不能为空');
            }
            $where['id'] = $params['id'];
            $where['mer_id'] = $this->adminUser['mer_id'];
            if (!empty($params['product_code'])) {
                $where['product_code'] = $params['product_code'];
            }
            Services::Virtual()->delPromoProduct($where);
            api_result([]);
        } catch (Exception $e) {
            api_result($e);
        }
    }

    /**
     * 虚码活动特殊规则列表
     */
    public function special_page()
    {
        try {
            $options = $this->makeSpecialWhere();
            $page = Services::Virtual()->getPromoSpecialPage($options);
            api_result($page);
        } catch (Exception $e) {
            api_result($e);
        }
    }

    /**
     * @title 根据请求,生成条件
     */
    private function makeSpecialWhere(): array
    {
        $params = $this->request->get();
        $options = $this->formatOption($params);
        $where = $where_raw = [];
        $mer_id = $this->adminUser['mer_id'];

        $where['mer_id'] = $mer_id;
        if (!empty($params['vp_id'])) {
            $where['vp_id'] = $params['vp_id'];
        }
        //商品code
        if (!empty($params['product_code'])) {
            $where['vp_id'] = ['in', function ($query) use ($params, $mer_id) {
                $query->name('virtual_promo_product')->where('product_code', $params['product_code'])->where('mer_id', $mer_id)->field('vp_id');
            }];
        }
        //标签
        if (!empty($params['tags_id'])) {
            $where_raw[] = "limit_way::jsonb @> '[{\"id\":" . (int)$params['tags_id'] . "}]'";
            $where['type'] = 1;
        }
        //门店
        if (!empty($params['shop_id'])) {
            $where_raw[] = "limit_way::jsonb @> '[{\"id\":" . (int)$params['shop_id'] . "}]'";
            $where['type'] = 2;
        }
        //导购
        if (!empty($params['sales_id'])) {
            $where_raw[] = "limit_way::jsonb @> '[{\"id\":" . (int)$params['sales_id'] . "}]'";
            $where['type'] = 3;
        }
        $options['where_raw'] = $where_raw;
        $options['where'] = $where;
        return $options;
    }

    /**
     * 虚码活动特殊规则编辑
     */
    public function special_save()
    {
        try {
            $params = $this->request->post();
            $params['mer_id'] = $this->adminUser['mer_id'];
            $params['op_user'] = $this->adminUser['admin_id'];
            $scene = '.add';
            if (!empty($params['id'])) {
                unset($params['op_user']);
                $scene = '.edit';
            }
            $this->validate($params, VirtualPromoSpecialValid::class . $scene);
            $id = Services::Virtual()->savePromoSpecial($params);
            api_result(['id' => $id]);
        } catch (Exception $e) {
            api_result($e);
        }
    }

    /**
     * 虚码活动特殊规则删除
     */
    public function special_del()
    {
        try {
            $id = $this->request->post('id', 0);
            if (empty($id)) {
                api_exception(400, 'ID不能为空');
            }
            Services::Virtual()->delPromoSpecial(['id' => $id]);
            api_result([]);
        } catch (Exception $e) {
            api_result($e);
        }
    }

    /**
     * 虚码活动特殊规则详情
     */
    public function special_info()
    {
        try {
            $id = $this->request->get('id', 0);
            if (empty($id)) {
                api_exception(400, 'ID不能为空');
            }
            $res = Services::Virtual()->getPromoSpecialInfo(['where' => ['id' => $id]]);
            api_result($res);
        } catch (Exception $e) {
            api_result($e);
        }
    }

    /**
     * 虚码规则编辑状态
     */
    public function edit_special_status()
    {
        try {
            $params = $this->request->post();
            $this->validate($params, VirtualPromoValid::class . '.edit_status');
            $id = Services::Virtual()->editSpecialStatus(['id' => $params['id'], 'mer_id' => $this->adminUser['mer_id']], ['status' => $params['status']]);
            api_result(['id' => $id]);
        } catch (Exception $e) {
            api_result($e);
        }
    }
}
